<template>
  <div class="add_info">
    <!-- 面包屑导航 -->
    <bread :item="['商品管理','添加商品']"></bread>
    <!-- 卡片视图 -->
    <el-card shadow="hover">
      <!-- 提示 -->
      <el-alert show-icon title="添加商品信息" center></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" :active="+activeIndex" finish-status="success" align-center>
        <el-step v-for="(item,i) in steps" :title="item" :key="i"></el-step>
      </el-steps>
      <!-- Tabs区域 -->
      <el-form :model="infoForm" :rules="infoRules" ref="infoForm" label-width="100px" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" 
            :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息">
            <scroll-plugin ref="info_scroll">
              <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="infoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="infoForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="infoForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="infoForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader expand-trigger="hover" :options="cates" 
               :props="cateProps" v-model="infoForm.goods_cat" @change="handleChange">

              </el-cascader>
            </el-form-item>
            </scroll-plugin>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <scroll-plugin ref="param_scroll">
                <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cd" v-for="(cd,i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            </scroll-plugin>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <scroll-plugin ref="attr_scroll">
              <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
               </el-form-item>
            </scroll-plugin>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
             <scroll-plugin ref="pic_scroll">
               <el-upload
                :action="uploadUrl" 
                :on-preview="handlePreview"
                :on-remove="handleRemove" :on-change="picRefresh"
                :auto-upload="false" :on-success="uploadSuc"
                ref="upload" list-type="picture"
                :headers="headers">
                <el-button slot="trigger" size="small" type="primary" >点击添加</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              </el-upload>
            </scroll-plugin>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="infoForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="viewVisible" width="50%">
       <el-image :src="viewPath"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import {bread,scrollPlugin,default as fn} from "tools"
import scroll from "better-scroll"
import _ from "lodash"
export default {
 components:{bread,scrollPlugin}
 ,data(){return{
    steps:['基本信息','商品参数','商品属性','商品图片','商品内容','完成']
   ,activeIndex:"0"
   ,tabPanes:['基本信息','商品参数','商品属性','商品图片','商品内容']
   //表单数据
   ,infoForm:{
     goods_name:""
    ,goods_price:null
    ,goods_weight:null
    ,goods_number:null
    //隶属的商品
    ,goods_cat:[]
    //图片
    ,pics:[]
    //商品详情
    ,goods_introduce:""
    ,attrs:[]
   }
   //表单验证
   ,infoRules:{
     goods_name:[{required:true,message:"请输入商品名称",trigger:'blur'}]
    ,goods_price:[{required:true,message:"请输入商品价格",trigger:"blur"}]
    ,goods_weight:[{required:true,message:"请输入商品重量",trigger:"blur"}]
    ,goods_number:[{required:true,message:"请输入商品数量",trigger:"blur"}]
    ,goods_cat:[{required:true,message:"请选择商品分类",trigger:"change"}]
   }
   //商品数据
   ,cates:[]
   ,cateProps:{
     label:"cat_name"
    ,value:"cat_id"
    ,children:"children"
   }
  //  动态参数获取
   ,manyTableData:[]
   //静态属性
   ,onlyTableData:[]
   //上传图片的url地址
   ,uploadUrl:"http://127.0.0.1:8888/api/private/v1/upload"
   //上传图片的请求头
   ,headers:{
     Authorization:window.sessionStorage.getItem('token')
   }
   ,viewPath:""
   ,viewVisible:false
   ,pic_scroll:null
  }}
 ,created(){
   this.getCates()
 }
 ,methods:{
   async getCates(){
     let {data:ret}= await this.$XHR.get('categories')
     if(ret?.meta?.status!==200)return fn.mg("error","获取数据失败")
     this.cates= ret?.data ? ret.data : []
   }
   //级联改变时
  ,handleChange(){
    if(this.infoForm.goods_cat.length!==3)this.infoForm.goods_cat=[]
  }
  ,beforeTabLeave(n,o){
    let fla=true
    for(let [key,val] of Object.entries(this.infoForm)){
           
      if({}.toString.call(val)==="[object Array]"){
        if(key === "goods_cat" && val.length!==3 ){         
          fla= false 
          break
        }
        break      
      }
        fla= !!val
        if(!fla)break       
    }
    
    if(!fla){
      fn.mg("error","请填写完整")
      return false
    }
  }
  //点击tabs栏时触发
  ,tabClicked(){
    if(this.activeIndex==='1'){
      this.getInfos('many',"manyTableData",true)
    }else if(this.activeIndex==="2"){
      this.getInfos("only","onlyTableData")
    }else if(this.activeIndex==='0'){
      this.$refs['info_scroll'].refresh()
    }  
  }
  ,async getInfos(t,v,i){
     const {data:ret}= await this.$XHR.get('categories/'+this.cateId+'/attributes',{
        params:{sel:t}})
     if(ret?.meta?.status!==200)return fn.mg("error","获取失败")
     //分割复选框
     i && ret?.data && ret.data.forEach(item=>{
      item.attr_vals= item.attr_vals.length!==0? item.attr_vals.split(" "): [] 
     })
     this[v]= ret?.data ? ret.data : []
     this.$refs['param_scroll'].refresh()
     this.$refs['attr_scroll'].refresh()
  }
  //处理图片预览
  ,handlePreview(f){
    this.viewPath=f.url ? f.url : ''
    this.viewVisible= true
  }
  //移出图片
  ,handleRemove(f){
    if(!f.response)return
    const fp= f.response.data.tmp_path
    const i= this.infoForm.pics.findIndex(item=>item.pic===fp)
    this.infoForm.pics.splice(i,1)
    this.$notify({
      title:"提示"
     ,message:"以删除,将不会被保存"
    })
  }
  //上传图片
  ,submitUpload(){
    this.$refs['upload'].submit()
  }
  //上传成功时触发
  ,uploadSuc(res){
    if(res.meta.status!==200)return fn.mg("error","上传失败!")
    const pic= {pic:res.data.tmp_path}
    this.infoForm.pics.push(pic)
    this.$notify({
      title:"提示"
     ,message:"上传成功，等待最终确认"
     ,type:"success"
    })
  }
 //当上传的图片超出盒子大小时刷新scroll
 ,picRefresh(){
   this.$refs['pic_scroll'].refresh()
 }
 ,addBtn(){
   //表单预校验
   this.$refs['infoForm'].validate(async bool=>{
     //未通过的提示
     if(!bool)return this.$notify({
       title:"提示"
      ,message:"商品的基本信息不完整"
      ,type:"warning"
     })
    //合法执行
    const form= _.cloneDeep(this.infoForm)
    //提交前先处理数据类型
    form.goods_cat= form.goods_cat.join(",")
    //处理动态参数
    this.manyTableData.forEach(item=>{
      const all={attr_id:item.attr_id,attr_value:item.attr_vals.join(' ')}
      form.attrs.push(all)
    })
    //处理静态参数
    this.onlyTableData.forEach(item=>{
      const all={attr_id:item.attr_id,attr_value:item.attr_vals}
      form.attrs.push(all)
    })
    //发起添加商品请求
    const {data:ret}= await this.$XHR.post("goods",form)
    if(ret?.meta?.status!==201)return fn.mg("error","创建失败")
    fn.mg("success","创建成功")
    this.$router.push('/goods')
   })
 }
 }
 ,computed:{
   cateId(){
     let cat= this.infoForm.goods_cat
     return cat.length===3 ? cat[2]:null
   }
 }

}
</script>

<style lang="less" scoped>
.el-steps{
  margin:15px 0;
  font-size: 12px;
}
.el-checkbox{
  margin: 0 8px 0 0  !important;
}
.addBtn{
  margin-top: 15px;
}
</style>